package com.example.music_project.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.music_project.R;
import com.example.music_project.dao.UserDbHelper;
/*编辑个人信息*/
public class EditProfileFragment extends Fragment {

    private EditText etUsername, etEmail;
    private Button btnSave;
    private UserDbHelper userDbHelper;
    private String currentUsername; // 从 ProfileFragment 传递过来的当前用户名

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_profile, container, false);

        etUsername = view.findViewById(R.id.et_username);
        etEmail = view.findViewById(R.id.et_email);
        btnSave = view.findViewById(R.id.btn_save);

        userDbHelper = new UserDbHelper(requireContext());

        // 获取从 ProfileFragment 传递过来的用户名
        assert getArguments() != null;
        currentUsername = getArguments().getString("username");

        // 加载当前用户信息到编辑框
        loadUserData();

        // 点击“保存”按钮
        btnSave.setOnClickListener(v -> saveUserData());

        return view;
    }

    /**
     * 加载当前用户信息到编辑框
     */
    private void loadUserData() {
        String email = userDbHelper.getEmailByUsername(currentUsername);
        etUsername.setText(currentUsername);
        etEmail.setText(email != null ? email : "");
    }

    /**
     * 保存修改后的用户信息
     */
    private void saveUserData() {
        String newUsername = etUsername.getText().toString().trim();
        String newEmail = etEmail.getText().toString().trim();

        if (newUsername.isEmpty() || newEmail.isEmpty()) {
            Toast.makeText(requireContext(), "用户名和邮箱不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新数据库
        boolean isUpdated = userDbHelper.updateUserInfo(currentUsername, newUsername, newEmail);

        if (isUpdated) {
            Toast.makeText(requireContext(), "保存成功", Toast.LENGTH_SHORT).show();

            // 返回 ProfileFragment，并传递新用户名（用于刷新数据）
            Bundle bundle = new Bundle();
            bundle.putString("username", newUsername);
            getParentFragmentManager().setFragmentResult("update_profile", bundle);

            // 返回上一页 手动弹出 Fragment
            getParentFragmentManager().popBackStack();
        } else {
            Toast.makeText(requireContext(), "保存失败（用户名可能已存在）", Toast.LENGTH_SHORT).show();
        }
    }
}